import { get, post } from '@/utils/request'
import { reactive } from 'vue'
import { date } from '@/utils/util'

const REFRESHTIMER = import.meta.env.VITE_APP_REFRSHTIMER ? +import.meta.env.VITE_APP_REFRSHTIMER : 5000

const store = reactive({
  indexMap: {
    BSESN: {},
    NSEI: {}
  },
  exchangeType: {
    XBOM: [],
    XNSE: []
  },
  exchangeMap: {},
  systemConfig: {},
  systemConfigMap: {}
})
let indexTimer = null
let stocksTimer = null

function getIndexDetail(code) {
  return get(`/th/fin/index/IND/daily/realtime?token=39308cb2fb97445898c3789df970032d&ticker=${code}&columns=ticker,date,close,pre_close`)
}
export async function finIndexDetail(duration) {
  if (indexTimer) {
    window.clearTimeout(indexTimer)
    indexTimer = null
  }
  indexTimer = setTimeout(async () => {
    const list = ['BSESN', 'NSEI'].map(e => getIndexDetail(e))
    const resList = await Promise.all(list)
    let obj = {}
    resList.forEach(e => {
      e.forEach(k => {
        const balance = (k.close - k.pre_close).toFixed(2)

        const rate = (balance / k.pre_close) * 100
        obj[k.ticker] = {
          ...k,
          balance: balance > 0 ? `+ ${balance}` : balance,
          isUp: balance > 0,
          rate: balance > 0 ? `+ ${rate.toFixed(2)}` : `${rate.toFixed(2)}`
        }
      })
    })
    store.indexMap = obj
    if(!checkExchangeTimeRage()) {
      window.clearTimeout(indexTimer)
      indexTimer = null
    } else {
      finIndexDetail()
    }
  }, duration || REFRESHTIMER)
}

const getXBOMList = () => post(`/api/app/stocks/list/`, {
  exchange_code: 'XBOM',
})
const getXNSEList = () => post(`/api/app/stocks/list/`, {
  exchange_code: 'XNSE',
})
export async function getExchangeStocks(duration) {
  if (stocksTimer) {
    window.clearTimeout(stocksTimer)
    stocksTimer = null
  }
  stocksTimer = setTimeout(async () => {
    const resList = await Promise.all([getXBOMList(), getXNSEList()])
    store.exchangeType.XBOM = resList[0]
    store.exchangeType.XNSE = resList[1]
    const keylens = Object.keys(store.exchangeMap).length
    if (!keylens) {
      Object.keys(store.exchangeType).forEach(k => {
        store.exchangeType[k].forEach(e => {
          store.exchangeMap[e.ticker] = {
            ...e,
            excode: k
          }
        })
      })
    }
    if(!checkExchangeTimeRage()) {
      window.clearTimeout(indexTimer)
      indexTimer = null
    } else {
      getExchangeStocks()
    }
  }, duration || REFRESHTIMER)
}

export async function getSysConfig() {
  try {
    const res = await get(`/api/app/getsysconfig/`, {})
    store.systemConfig = res
    store.systemConfigMap = res.reduce((o, v) => {
      o[v.key] = v
      return o
    }, {})
    console.log(store.systemConfigMap)
  } catch (error) {
    console.log(error)
  }
}


export function checkExchangeTimeRage() {
  const systemConfig = store.systemConfig
  const ymd = date(new Date(), 'YYYY-MM-DD')
  let start = systemConfig.find(e => e.key === 'trade_start_time')
  let end = systemConfig.find(e => e.key === 'trade_end_time')
  start = new Date(`${ymd} ${start.value}:00`).getTime()
  end = new Date(`${ymd} ${end.value}:00`).getTime()
  const now = Date.now()
  const day = new Date().getDay()
  return now >= start && now < end && ![6,7].includes(day)
}





export default store
